// stdafx.cpp : source file that includes just the standard includes
// TextureSynthesizer.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"
#include <vcclr.h>

using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Imaging;

void StringToCharPointer(String^ string, char* output, int size)
{
	pin_ptr<const __wchar_t> p = PtrToStringChars(string);
	wcstombs_s(NULL, output, size, p, size);
}


IplImage* BitmapToIplImage(Bitmap^ bitmap)
{
	if(bitmap->PixelFormat != PixelFormat::Format24bppRgb && bitmap->PixelFormat != PixelFormat::Format8bppIndexed)
	{
		throw gcnew Exception("Un-Supported Image Format");
	}

	if(bitmap->PixelFormat == PixelFormat::Format24bppRgb)
	{
		IplImage* img = cvCreateImage(cvSize(bitmap->Width, bitmap->Height), 8, 3);
		BitmapData^ bitmapData = bitmap->LockBits(System::Drawing::Rectangle(0,0,bitmap->Width, bitmap->Height), ImageLockMode::ReadWrite, PixelFormat::Format24bppRgb);

		memcpy(img->imageData, bitmapData->Scan0.ToPointer(), img->widthStep*img->height*sizeof(char));

		bitmap->UnlockBits(bitmapData);
		return img;
	}
	else
	{
		IplImage* img = cvCreateImage(cvSize(bitmap->Width, bitmap->Height), 8, 1);
		BitmapData^ bitmapData = bitmap->LockBits(System::Drawing::Rectangle(0,0,bitmap->Width, bitmap->Height), ImageLockMode::ReadWrite, PixelFormat::Format8bppIndexed);

		memcpy(img->imageData, bitmapData->Scan0.ToPointer(), img->widthStep*img->height*sizeof(char));

		bitmap->UnlockBits(bitmapData);
		return img;
	}
}

Bitmap^ IplImageToBitmap(IplImage* img)
{

	if((img->nChannels != 1 &&  img->nChannels != 3) || img->depth != 8)
	{
		throw gcnew Exception("Un-Supported Image Format");
	}

	Bitmap^ bitmap;

	if(img->nChannels == 3)
	{
		bitmap = gcnew Bitmap(img->width, img->height, PixelFormat::Format24bppRgb);
		BitmapData^ bitmapData = bitmap->LockBits(System::Drawing::Rectangle(0,0,bitmap->Width, bitmap->Height), ImageLockMode::ReadWrite, PixelFormat::Format24bppRgb);
		memcpy(bitmapData->Scan0.ToPointer(), img->imageData, img->widthStep*img->height*sizeof(char));
		bitmap->UnlockBits(bitmapData);
	}
	else
	{
		IplImage* colord = cvCreateImage(cvGetSize(img),8,3);
		cvConvertImage(img, colord);
		bitmap = gcnew Bitmap(img->width, img->height, PixelFormat::Format24bppRgb);
		BitmapData^ bitmapData = bitmap->LockBits(System::Drawing::Rectangle(0,0,bitmap->Width, bitmap->Height), ImageLockMode::ReadWrite, PixelFormat::Format24bppRgb);
		memcpy(bitmapData->Scan0.ToPointer(), colord->imageData, colord->widthStep*colord->height*sizeof(char));
		bitmap->UnlockBits(bitmapData);
		cvReleaseImage(&colord);
	}

	return bitmap;
}